<?php if(!defined('SYSPATH')) die ('Yêu cầu không hợp lệ');

class database{
    protected $connect=null;
    protected $hostname='localhost';
    protected $userdb='root';
    protected $passdb='';
    protected $dbname='cms';
    protected $query=null;
    // Ham ket noi CSDL        
    function db_connect(){
        $this->connect =  mysql_connect($this->hostname, $this->userdb, $this->passdb);  
        if (!$this->connect){
            die('Không thể kết nối tới database'.mysql_errno());
        }else{
            mysql_select_db($this->dbname, $this->connect);
            mysql_query("SET NAMES 'utf8'");
        }
   
    }
    //Ham thuc hien truy van
    function db_select_list($sql){
        $this->query = mysql_query($sql, $this->connect);
        if (!$this->query){
            die('Cau truy van khong dung');
        }
        while($row = mysql_fetch_array($this->query, MYSQL_ASSOC)){
            $list[] = $row;
        }
        mysql_free_result($this->query);
        return $this->query;
   
    }
    // tổng số bản ghi
    function db_count(){
         $this->query = mysql_query($sql, $this->connect);
        if (!$this->query){
            die('Cau truy van khong dung');
        }
        $row = mysql_fetch_array($this->query,MYSQL_ASSOC);
        mysql_free_result($this->query);
        return $row;
        
   
    }
    // lấy từng dòng
    function db_select_row($sql){
        $this->query = mysql_query($sql, $this->connect);
        if (!$this->query){
            die('Cau truy van khong dung');
        }
        $row = mysql_fetch_array($this->query,MYSQL_ASSOC);
        mysql_free_result($this->query);
        return $row;
   
    }
    // insert dữ liệu
    function db_insert($table,$data=  array()){
        $field='';
        $value='';
        foreach ($data as $key=>$val){
            $field .=$key.',';
            $value .="'".mysql_escape_string($val)."'".',';
            $sql = "INSERT INTO $table (trim($field,',')) VALUES $value";
            return mysql_query($sql, $this->connect);
        }
   
    }
    //update dữ liệu
    function db_update_by_id($table, $idfield, $idvalue, $data = array()){
        $in_tmp = '';
        foreach ($data as $key=>$val){
            $in_tmp .= $key.'='. mysql_escape_string($val).',';
            
        }
        $sql= "UPDATE $table SET (trim($in_tmp,',')) WHERE $idfield = (int)$idvalue";
        return mysql_query($sql, $this->connect);
        
   
    }
    //Xóa
    function db_delete_by_id($table, $idfield, $idvalue){
        
        $sql = "DELETE FORM $table WHERE $idfield =".$idvalue;
        return mysql_query($sql, $this->connect);
   
    }
    // Đóng kết nối
    function db_disconnect(){
        mysql_close($this->connect);
   
    }
    
    
    
    
    
    
    
    
    
    
}
?>
